import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router'
import axios from '@/utils/request'

export const useAuthStore = defineStore('auth', () => {
    const token = ref(localStorage.getItem('token'))
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))

// 登录方法
    const login = async (credentials) => {
        try {
            const response = await axios.post('/auth/login', credentials)

            const tokenStr = response.data?.data

            if (!tokenStr || typeof tokenStr !== 'string') {
                throw new Error('登录失败：服务器未返回Token')
            }

            // 解析 token 的 payload（不验证签名，仅解码 base64）
            const base64Payload = tokenStr.split('.')[1]
            const payloadJson = atob(base64Payload)
            const payload = JSON.parse(payloadJson)

            // 可以根据 payload 里的内容设置用户信息
            const username = payload.sub
            const user = { username }

            // 保存 token 和用户信息
            localStorage.setItem('token', tokenStr)
            localStorage.setItem('userInfo', JSON.stringify(user))

            token.value = tokenStr
            userInfo.value = user

            router.push('/')
            return true
        } catch (error) {
            console.error('登录请求错误详情:', error.response?.data || error.message)
            throw new Error(error.response?.data?.message || '登录失败，请检查凭证')
        }
    }

    // 登出方法
    const logout = () => {
        token.value = null
        userInfo.value = null
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        router.push('/login')
    }

    // 检查登录状态
    const isAuthenticated = () => {
        return !!token.value
    }

    return {
        token,
        userInfo,
        login,
        logout,
        isAuthenticated
    }
})